// pages/order-pay/order-pay.js
import { storeApi, commonApi } from '../../api/index';
import { wxPay } from "../../utils/wxPayment";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    showLoginTipPopup: false,
    isCheck: false,
    isVIP: false,
    vipPrice: 19.9, // vip价格
    id: null,
    order_info: {},
    store_info:{},
    buttonClicked: true, //是否可点击付款
    show_coupon: false, //显示优惠券弹层
    currentBonusId: null,
    currentBonusText: "",
    canuseList: [], //可用优惠券列表
    // unuseList: [], //不可用优惠券列表
    pageParam: {
      page: 1,
      page_size: 20
    },
    payAgain: false, // 是否已经支付过没成功，再次点支付
    costPrice: {},
  },
  async getUserInfo() {
    try {
      let res = res = await commonApi.getUserInfo()
      this.setData({
        isVIP: Number(res.is_vip),
        showLoginTipPopup: res.phone ? false : true,
        phone: res.phone,
      })
      this.checkOrder();
    } catch (e) { }
  },
  async checkOrder(){
    try {
      const {showLoginTipPopup, phone} = this.data
      if(!showLoginTipPopup && phone){
        let res = res = await storeApi.queryRanstoreReservationOrderList({
          page: 1,
          page_size: 20,
          status: 4 // 获取用户待支付订单
        })
        this.setData({
          list: res.list || [],
        })
        console.log(this.data.list)
        if(res.list.length === 1){
          await this.getInfo()
          this.getVipPrice()
          // this.getCanUserCoupon()
        } else if (res.list.length > 1){
          wx.reLaunch({
            url: `/pages/order/order?checkedTab=4`,
          })
        } else {
          wx.reLaunch({
            url: `/pages/me/me`,
          })
        }
      }
    } catch (e) { 
      console.log(e)
    }
  },
  async getInfo() {
    try {
      const id = this.data.list[0].id
      const res = await storeApi.getReservationOrderDetail({ id })
      this.setData({
        id,
        order_info: res,
        store_info: res.store_info,
      })
      if(res?.pay_transaction_info?.id){
       // 用于已经点过支付的但没支付成功的订单再次调起支付
        const currenCoupon = res.coupon_list.find(item => item.coupon_id == res.coupon_ids);
        this.setData({
          payAgain: true,
          currentBonusId: res.coupon_ids,
          currentBonusText: currenCoupon.desc,
          canuseList: res.coupon_list,
          isCheck: res.buy_vip == 1 ? true : false,
          costPrice:{
            final_amount:res.final_amount,
            discount_amount: res.discount_amount,
          }
        })
      }else{
        this.getCanUserCoupon()
      }
    } catch (e) { }
  },
  toNavigation(){
    const store_info = this.data.store_info
    wx.openLocation({
      latitude: store_info.address_coordinate_latitude || 39.90469,  // 目标纬度，浮点数，范围为-90~90
      longitude: store_info.address_coordinate_longitude ||  116.40717, // 目标经度，浮点数，范围为-180~180
      name: store_info.name || '天安门广场',    // 位置名
      address: store_info.address || '北京市东城区', // 详细地址
      scale: 16,           // 地图缩放级别，整形值，范围从1~28
      success: function() {
        console.log('打开地图成功');
      },
      fail: function(err) {
        console.error('打开地图失败:', err);
      }
    })
  },
  async getVipPrice() {
    try {
      let res = res = await storeApi.getVipPrice()
      this.setData({
        vipPrice: res.final_amount / 100,
      })
    } catch (err) {
       console.log('err', err)
     }
  },
  showCoupon() {
    if(this.data.payAgain) return
    //点击优惠券显示更多
    this.setData({
        show_coupon: true
    });
  },
  clickCouponLayer() {
    this.setData({
        show_coupon: false,
        show_all_coupon: false,
    })
  },
  choiceCoupon(e) {
    let dataset = e.currentTarget.dataset;
    //点击切换优惠券
    this.setData({
      show_coupon: false,
      currentBonusId: dataset.id,
      currentBonusText: dataset.desc,
    })
    this.getProjectPrice();
  },
  async getCanUserCoupon() {
    try {
      const { isCheck, pageParam } = this.data
      const res = await storeApi.queryUserCouponList({
        ...pageParam,
        use_status: 1,
        buy_vip: isCheck ? 1 : 0,
      })
      let list = res.list;
      this.setData({
        currentBonusId: list.length > 0 ? list[0].coupon_id : '',
        currentBonusText: list.length > 0 ? list[0].desc : '',
        canuseList: list,
      })
      this.getProjectPrice();
    } catch (e) { 
      console.log(e)
    }
  },
  async getProjectPrice() {
    try {
      const { isCheck, order_info, currentBonusId } = this.data
      const res = await storeApi.getProjectPrice({
        ran_store_hairdye_type_id: order_info.hairdye_type_info.id,
        ran_store_hairdye_color_id: order_info.hairdye_color_info.id,
        ran_store_hair_region_id: order_info.hair_region_info.id,
        buy_vip: isCheck ? 1 : 0,
        coupon_ids: currentBonusId+""
      })
       console.log(res)
      this.setData({
        costPrice: res,
      })
    } catch (e) {
      console.log(e)
     }
  },
  async onCreatOrder() {
      try {
          let self = this
          self.setData({
              buttonClicked: false
          })
          wx.showLoading({
              title: '支付中',
          })
          const {id , isCheck, order_info, currentBonusId } =  this.data
          let resp = null
          if(order_info?.pay_transaction_info?.id){
            // 用于已经点过支付的但没支付成功的订单再次调起支付
             resp = await storeApi.getPayInfo({
              reservation_order_id: id,
            })
          } else{
            resp = await storeApi.createRanstorePayOrder({
              reservation_order_id: id,
              buy_vip: isCheck ? 1 : 0,
              scene: 11,
              coupon_ids: currentBonusId+"",
              product_name: `${order_info.hairdye_type_info.name}_${order_info.hairdye_color_info.name}_${order_info.hair_region_info.name}`,
              //  user_remark: ""
            })
          }
          const payParam = {...resp,order_type: 'order'}
          console.log(payParam)
          wxPay(payParam);
          wx.hideLoading();
          self.data.clickRepeatTimer = setTimeout(function () {
              self.setData({
                  buttonClicked: true
              })
          }, 1000)
      } catch (err) {
          console.log(err)
          this.setData({
              buttonClicked: true
          })
          this.getInfo()
      }
    },
  checkboxChange() {
    if(this.data.payAgain) return
    this.setData({
      isCheck: !this.data.isCheck,
    }, ()=>{
       this.getCanUserCoupon();
    });
  },
  cancelLoginTipPopup(event) {
    let val = event.detail;
    console.log(val.phoneNumber)
    this.setData({
      showLoginTipPopup: false,
      phone: val.phoneNumber
    },async ()=>{
      this.getUserInfo();
    });
    // console.log(this.data.phone)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '频繁染白发，就找染博士',
      imageUrl:
        'https://ranboss.oss-cn-beijing.aliyuncs.com/ranstore/share.png',
    };
  },
});
